<template>
    <div class="continer">
        <baidu-map-location
            class="map"
            width="100%"
            ref="baidumap"
            :address="address"
            :username="username"
            @changedPosition="onChangedPosition"
        />

        <div class="content">
            <div class="cells">
                <van-cell
                    center
                    title=""
                    is-link
                    clickable
                    class="cell"
                    @click="onClickShowAddress"
                    :value="address.title"
                >
                    <template #title>
                        <span class="red">*</span>
                        <span class="customer">{{$st('wp_Address')}}</span>
                    </template>
                    <template #label>
                        <van-icon name="location-o" />{{$st('wp_Click_to_locate')}}
                    </template>
                </van-cell>

                <van-cell

                    class="cell"
                    is-link
                    :value="status.name"
                    @click="showStatus = true">
                    <template #title>
                        <span class="red">*</span>
                        <span class="customer">{{$st('wp_State')}}</span>
                    </template>
                </van-cell>
                <van-cell
                    border
                    class="cell"
                    :title="$st('wp_Current_Customer')"
                    is-link
                    :value="selectedCustomer.label"
                    @click="selectCustomershow = true">

                </van-cell>
                <van-cell style="height:0px;padding:0px"></van-cell>
            </div>
            <div
                class="outer-state"
                @click="checkinMethod">
                <div class="state">
                    <div class="info">{{$st('wp_Check_in')}}</div>
                    <div class="time">{{ currentTime }}</div>
                </div>
            </div>
            <van-action-sheet
                :title="$st('wp_Nearby_Address')"
                :close-on-click-action="true"
                style="height: 100%"
                v-model:show="showAddresses"
            >
                <van-cell
                    clickable
                    @click="onSelectAddress(item)"
                    v-for="(item, index) in addresses"
                    :title="item.title"
                    :label="item.address"
                    :key="index"
                />
            </van-action-sheet>
            <van-action-sheet
                v-model:show="showStatus"
                :actions="[
                    { name: $st('wp_Unknown'), value: '0' },
                    { name: $st('wp_Working'), value: '1' },
                    { name: $st('wp_Standby'), value: '2' },
                    { name: $st('wp_Resting'), value: '3' },
                ]"
                :cancel-text="$st('wp_Cancel')"
                close-on-click-action
                @select="onStatusSelect"
            />
            <popup-search-index-bar
                v-model="selectCustomershow"
                :data="customers"
                displayField="label"
                @selectedItem="companySelected"
            />
        </div>
    </div>
    <van-dialog
        v-model:show="show"
        :confirmButtonText="$st('wp_I_see')"
        confirmButtonColor="black"
        width="290px"
    >
        <div class="dialg-container">
            <van-image
                class="image-container"
                :src="require('@/assets/icon_260_checkin.png')"
            >
            </van-image
            ><br />
            <label class="tipslabel">{{$st('wp_Check_in_successfully')}}</label>
            <div class="timestatus">
                <label class="timelabel">{{ currentTime + " " + status.name }}</label>
            </div>
        </div>
    </van-dialog>
</template>
<script>
import {
    ref,
    toRefs,
    reactive,
    onMounted,
    onBeforeUnmount,
    computed
} from 'vue';
import Cookies from 'js-cookie';
import { Toast } from 'vant';
import BaiduMapLocation from './BaiduMapLocation.vue';
import PopupSearchIndexBar from '@/components/_common/PopupSearchIndexBar.vue';
import useMaintenanceInfoSetup from '@/setup/maintenanceteam/MaintenanceCustomInfoSetup';
import { putMemberClock, jssdksignature } from '@/api/server';
import { apiService } from '@/api/apiService';
import { showError } from '@/util/MessageDeal';
// import { useRouter } from 'vue-router';
import wx from 'weixin-js-sdk';
import { selfI18n } from '@/i18n';

export default {
    components: { BaiduMapLocation, PopupSearchIndexBar },
    setup () {
        const username = Cookies.get('username');
        const { queryCustomerRecorf } = useMaintenanceInfoSetup();
        // const router = useRouter();
        const baidumap = ref(null);
        const status = ref({ name: '' });
        const showStatus = ref(false);
        const show = ref(false);

        // const location = null;
        const selectCustomershow = ref(false);
        const selectedCustomer = ref({ lable: '' });

        const state = reactive({
            addresses: [],
            showAddresses: false,
            selectAddress: {
                title: '',
                address: '',
                point: { lng: 0.0, lat: 0.0 }
            }
        });
        const address = computed(() => {
            return state.selectAddress;
        });
        const $st = selfI18n;
        const onChangedPosition = (result) => {
            state.selectAddress = {
                title: result.title,
                address: result.address,
                point: result.point
            };
            state.addresses = [];
            state.addresses.push(...result.surroundingPois);
        };

        const onClickShowAddress = () => {
            state.showAddresses = true;
        };
        // 选择一个地址
        const onSelectAddress = (item) => {
            state.selectAddress = item;
            state.showAddresses = false;
        };

        // 获取微信定位授权
        const getWxPosition = (success) => {
            const param = {};
            if (window.__wxjs_is_wkwebview) {
                param.isios = true;
            }
            apiService({
                api: jssdksignature,
                param: param,
                success: (data) => {
                    wx.config({
                        debug: false,
                        appId: data.values.appId,
                        timestamp: data.values.timestamp,
                        nonceStr: data.values.nonceStr,
                        signature: data.values.signature,
                        jsApiList: ['getLocation', 'openLocation']
                    });
                    success && success();
                }
            });
        };

        const getLocAddress = () => {
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: (res) => {
                    const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    // const speed = res.speed; // 速度，以米/每秒计
                    // const accuracy = res.accuracy; // 位置精度
                    // console.log(latitude, longitude)
                    // 转换为百度坐标轴然后获取地址
                    convertToBDPoint({
                        lat: latitude,
                        lng: longitude
                    });
                    // console.log(latitude + ',' + longitude);
                },
                fail: (err) => {
                    console.log(err);
                }
            });
        };

        /** 根据坐标点获取地址 */
        const getAddresses = (point) => {
            const mapGeo = new BMap.Geocoder();
            mapGeo.getLocation(
                point,
                (result) => {
                    if (result) {
                        let addresses = [];
                        if (result.surroundingPois.length >= 0) {
                            addresses = result.surroundingPois;
                        } else {
                            addresses = [result];
                        }
                        //  console.log(JSON.stringify(result));
                        state.selectAddress = {
                            title: result.address,
                            address: result.address,
                            point: result.point
                        };
                        state.addresses = [];
                        state.addresses.push(...addresses);
                    }
                },
                {
                    // 半径
                    poiRadius: 1000,
                    // 返回数目
                    numPois: 100
                }
            );
        };

        // 转换地址
        const convertToBDPoint = (point) => {
            const bdPoint = new BMap.Point(point.lng, point.lat);
            const bdConvert = new BMap.Convertor();
            const bdPoint_array = [bdPoint];
            bdConvert.translate(bdPoint_array, 1, 5, (data) => {
                if (data.status === 0) {
                    getAddresses(data.points[0]);
                }
            });
        };

        const checkinMethod = () => {
            console.log(address.value);
            if (!address.value || !status.value.name || !address.value.address) {
                showError(selfI18n('wp_Please_locate_and_select_the_working_status'));
                return;
            }
            apiService({
                api: putMemberClock,
                param: {
                    address: address.value.address,
                    customer_id: selectedCustomer.value.value,
                    customer_name: selectedCustomer.value.label,
                    location:
            address.value.point.lng.toFixed(5) +
            ', ' +
            address.value.point.lat.toFixed(5),
                    status: status.value.value
                },
                success: (data) => {
                    show.value = true;
                }
            });
        };
        const onStatusSelect = (item) => {
            status.value = item;
        };
        const customers = reactive([]);

        queryCustomerRecorf().then((response) => {
            response.value.map((item) => {
                customers.push({ value: item.customer_id, label: item.customer_name });
            });
        });

        const companySelected = (item) => {
            selectedCustomer.value = item;
        };

        const getLocation = () => {
            baidumap.value.getLocation();
        };
        const currentTime = ref('');
        const timer = setInterval(() => {
            const date = new Date();
            const h = date.getHours();
            const m = date.getMinutes();
            const hour = h > 9 ? h : '0' + h;
            const min = m > 9 ? m : '0' + m;
            currentTime.value = hour + ':' + min;
        }, 1000);
        onBeforeUnmount(() => {
            clearInterval(timer);
        });
        onMounted(() => {
            getWxPosition(() => {
                wx.ready(() => {
                    wx.checkJsApi({
                        jsApiList: [
                            'getLocation'
                        ],
                        success: function (res) {
                            if (res.checkResult.getLocation === false) {
                                Toast(selfI18n('wp_WeChat_edition_too_low'));
                            } else {
                                getLocAddress();
                            }
                        },
                        error: function (res) {
                            console.log(res);
                        }
                    });
                    wx.error(() => {
                        ($st('wp_Failed_to_obtain_the_address_information_permission'));
                    });
                });
            });
        });
        return {
            username,
            show,
            address,
            status,
            showStatus,
            customers,
            selectCustomershow,
            selectedCustomer,
            checkinMethod,
            companySelected,
            onStatusSelect,
            getLocation,
            baidumap,
            currentTime,
            onClickShowAddress,
            onSelectAddress,
            onChangedPosition,
            ...toRefs(state)
        };
    }
};
</script>
<style lang="scss" scoped>
.red {
  color: red;
}
.continer {
  height: 620px;
  border-radius: 12px;
  margin: 15px;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
   background: #fff;
  position: relative;
  overflow: hidden;
}
.map {
  z-index: 9;
  height: 300px;
  width: 100%;

  background-color: #1890ff;
}
.content {

  width: 100%;
  height: 100%;
  .cells {
    border-top: 1px solid var(--van-cell-border-color);
    :deep(.van-cell__title) {
      color: #000000;
      font-size: 17px;
    }
    :deep(.van-cell__value) {
      font-size: 16px;
      color: #888888;
    }
    .cell {
        padding-left:15px;
        padding-right:15px
    }
  }
}
.outer-state {
  width: 120px;
  height: 120px;
  padding: 10px;
  margin: 20px auto 48px auto;
  border-radius: 50%;
  box-sizing: border-box;
  background: rgba(24, 144, 255, 0.2);
  .state {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    text-align: center;
    background: #1890ff;
    color: #ffffff;
    .info {
      padding-top: 25px;
      height: 36px;
      font-size: 24px;
    }
    .time {
      font-size: 15px;
    }
  }
  &:active {
    transform: scale(0.95);
  }
}
.dialg-container {
  width: 290px;
  opacity: 1;
  background: #ffffff;
  border-radius: 6px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
    padding: 20px;
  .image-container {
    width: 130px;
    opacity: 1;
    vertical-align: middle;
  }
  .tipslabel {
    width: 96px;
    height: 36px;
    opacity: 1;
    font-size: 24px;
    font-weight: 500;
    text-align: center;
    color: #1890ff;
    vertical-align: middle;
  }
  .timestatus {
    vertical-align: middle;
    margin-top: 10px;
    .timelabel {
      width: 82px;
      height: 20px;
      opacity: 1;
      font-size: 14px;
      font-weight: 500;
      text-align: center;
      color: #1890ff;
      line-height: 20px;
    }
  }
}
</style>
